(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global[""] = global[""] || {}, global[""]["/dist"] = {})));
})(this, (function (exports) { 'use strict';

    var storage = {
        setSession: function (key, value) {
            var type = typeof value;
            if (type === 'string') {
                sessionStorage.setItem(key, "\"".concat(value, "\""));
            }
            else {
                sessionStorage.setItem(key, JSON.stringify(value));
            }
        },
        getSession: function (key) {
            var ret = sessionStorage.getItem(key) || '';
            if (ret) {
                try {
                    return JSON.parse(ret);
                }
                catch (e) {
                    return ret;
                }
            }
            return '';
        },
        setLocal: function (key, value) {
            var type = typeof value;
            if (type === 'string') {
                localStorage.setItem(key, "\"".concat(value, "\""));
            }
            else {
                localStorage.setItem(key, JSON.stringify(value));
            }
        },
        getLocal: function (key) {
            var ret = localStorage.getItem(key) || '';
            if (ret) {
                try {
                    return JSON.parse(ret);
                }
                catch (e) {
                    return ret;
                }
            }
            return '';
        },
        clearSession: function (key) {
            if (key) {
                sessionStorage.removeItem(key);
            }
            else {
                sessionStorage.clear();
            }
        },
        clearLocal: function (key) {
            if (key) {
                localStorage.removeItem(key);
            }
            else {
                localStorage.clear();
            }
        }
    };

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    var __assign = function () {
      __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];

          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }

        return t;
      };

      return __assign.apply(this, arguments);
    };
    function __spreadArray(to, from, pack) {
      if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
        }
      }
      return to.concat(ar || Array.prototype.slice.call(from));
    }

    var jRequest = /** @class */ (function () {
        function jRequest(props) {
            var _this = this;
            this._times = 1;
            this._headers = {};
            this._request = function (requestOption, moduleName, apiName) {
                if (requestOption === void 0) { requestOption = { url: '', method: 'GET' }; }
                var options = {
                    headers: {},
                    method: 'get'
                };
                var url = requestOption.url, headers = requestOption.headers, method = requestOption.method, body = requestOption.body, isFormData = requestOption.isFormData;
                options.method = method;
                options.headers = Object.assign(_this._headers, headers);
                if (method.toLowerCase() !== 'get') {
                    if (isFormData) {
                        options.body = body;
                        delete options.headers['Content-Type'];
                    }
                    else {
                        if (_this._bodyPip) {
                            options.body = _this._bodyPip(body);
                        }
                        else {
                            options.body = JSON.stringify({ data: body });
                        }
                    }
                }
                var optResult = {
                    url: url,
                    options: options
                };
                if (_this._beforeRequest) {
                    optResult = _this._beforeRequest(url, options);
                }
                return new Promise(function (resolve, reject) {
                    fetch(optResult.url, optResult.options)
                        .then(function (res) {
                        return _this._beforeResponse(res);
                    })
                        .then(function (res) {
                        _this._times++;
                        _this._afterResponse(function () {
                            _this._times = 1;
                            resolve(res);
                        }, res, function () {
                            if (_this._times > _this._retry) {
                                return;
                            }
                            else {
                                _this._request(requestOption, moduleName, apiName);
                            }
                        });
                    })
                        .catch(function (err) {
                        _this._errorResponse(function () {
                            _this._times = 1;
                            reject(err);
                        });
                    });
                });
            };
            this.registerModule = function (module) {
                //@ts-ignore
                var moduleF = {
                    name: module.name
                };
                Object.keys(module).map(function (mKey) {
                    moduleF[mKey] = function (params) {
                        if (params === void 0) { params = {}; }
                        var query = params.query, path = params.path, body = params.body, headers = params.headers;
                        if (mKey === 'name') {
                            return module.name;
                        }
                        //@ts-ignore
                        var url = module[mKey].url;
                        //@ts-ignore
                        var _a = module[mKey], method = _a.method, isFormData = _a.isFormData;
                        //处理path参数
                        if (Array.isArray(path) && path.length > 0) {
                            url += path.join('/');
                        }
                        //处理query参数
                        if (query && Object.keys(query).length > 0) {
                            var arr = [];
                            var queryStr = '';
                            for (var k in query) {
                                if (k) {
                                    if (query[k]) {
                                        arr.push("".concat(k, "=").concat(encodeURIComponent(query[k])));
                                    }
                                    else {
                                        arr.push("".concat(k, "=").concat(query[k]));
                                    }
                                }
                            }
                            if (arr.length > 0) {
                                queryStr = '?' + arr.join('&');
                            }
                            url = url + queryStr;
                        }
                        return _this._request({
                            url: url,
                            method: method,
                            headers: headers,
                            body: body,
                            isFormData: isFormData
                        }, module.name, mKey);
                    };
                });
                return moduleF;
            };
            var _a = props.beforeResponse, beforeResponse = _a === void 0 ? function (res) { return res.json(); } : _a, _b = props.headers, headers = _b === void 0 ? {} : _b, _c = props.retry, retry = _c === void 0 ? 2 : _c, _d = props.bodyPip, bodyPip = _d === void 0 ? function (data) {
                return JSON.stringify({
                    data: data
                });
            } : _d, _e = props.afterResponse, afterResponse = _e === void 0 ? function (resolve) {
                resolve();
            } : _e, _f = props.errorResponse, errorResponse = _f === void 0 ? function (reject) {
                reject();
            } : _f, _g = props.beforeRequest, beforeRequest = _g === void 0 ? undefined : _g;
            this._retry = retry;
            this._bodyPip = bodyPip;
            this._headers = __assign({ 'Content-Type': 'application/json; charset=UTF-8' }, headers);
            this._beforeResponse = beforeResponse;
            this._beforeRequest = beforeRequest;
            this._afterResponse = afterResponse;
            this._errorResponse = errorResponse;
        }
        return jRequest;
    }());

    var Socket = /** @class */ (function () {
        function Socket(socketProp) {
            var _this = this;
            this.instance = null;
            this.taskRemindInterval = null;
            this.isSuccess = true;
            this.reconnect = true;
            this.socketProp = {
                url: '',
                socketOpen: function () { return null; },
                socketError: function () { return null; },
                socketMessage: function () { return null; },
                socketClose: function () { return null; }
            };
            this.connection = function () {
                if ('WebSocket' in window) {
                    var _a = _this.socketProp, url = _a.url, _b = _a.timeout, timeout = _b === void 0 ? 0 : _b;
                    _this.instance = new WebSocket(url);
                    _this.instance.onopen = _this.onopen;
                    _this.instance.onmessage = _this.onmessage;
                    _this.instance.onclose = _this.onclose;
                    _this.instance.onerror = _this.onerror;
                    //@ts-ignore
                    _this.instance.sendMessage = _this.sendMessage;
                    if (timeout) {
                        var time_1 = setTimeout(function () {
                            if (_this.instance && _this.instance.readyState !== 1) {
                                _this.instance.close();
                            }
                            clearTimeout(time_1);
                        }, timeout);
                    }
                    return;
                }
            };
            this.onmessage = function (msg) {
                var socketMessage = _this.socketProp.socketMessage;
                socketMessage && socketMessage(msg);
            };
            this.onopen = function () {
                var socketOpen = _this.socketProp.socketOpen;
                _this.isSuccess = false; //连接成功将标识符改为false
                socketOpen && socketOpen();
            };
            this.onerror = function (e) {
                var socketError = _this.socketProp.socketError;
                _this.instance = null;
                socketError && socketError(e);
            };
            this.onclose = function (e) {
                _this.isSuccess = true; //关闭将标识符改为true
                var socketClose = _this.socketProp.socketClose;
                socketClose && socketClose(e);
                if (e && e.code === '4500') {
                    _this.instance && _this.instance.close();
                }
                else {
                    _this.taskRemindInterval = setInterval(function () {
                        clearInterval(_this.taskRemindInterval);
                        if (_this.isSuccess && _this.reconnect) {
                            _this.connection();
                        }
                    }, 10000);
                }
            };
            this.sendMessage = function (value) {
                // 向后端发送数据
                if (_this.instance && _this.instance.readyState === 1) {
                    _this.instance.send(value);
                }
            };
            this.socketProp = socketProp;
        }
        return Socket;
    }());

    var JArr = /** @class */ (function () {
        function JArr() {
            this._translate = function (config) {
                if (config === void 0) { config = {}; }
                //@ts-ignore
                if (Array.isArray(this)) {
                    //@ts-ignore
                    var self = __spreadArray([], this, true);
                    var result_1 = [];
                    self.map(function (item) {
                        var temp = __assign({}, item);
                        Object.keys(config).map(function (key) {
                            temp[config[key]] = temp[key];
                            delete temp[key];
                        });
                        result_1.push(temp);
                    });
                    return result_1;
                }
            };
            //去重 unique
            this._unique = function () {
                //@ts-ignore
                if (Array.isArray(this)) {
                    //@ts-ignore
                    var self = __spreadArray([], this, true);
                    //@ts-ignore
                    return __spreadArray([], new Set(self), true);
                }
            };
            //扁平化 inline
            this._inline = function (key) {
                //@ts-ignore
                if (Array.isArray(this)) {
                    var getFlatTreeData_1 = function (treeData, result) {
                        var treeResult = result || [];
                        treeData.map(function (item) {
                            treeResult.push(item);
                            if (Array.isArray(item[key]) && item.children.length > 0) {
                                getFlatTreeData_1(item[key], treeResult);
                            }
                        });
                        return treeResult || [];
                    };
                    //@ts-ignore
                    var self = __spreadArray([], this, true);
                    return getFlatTreeData_1(self);
                }
            };
            //finds //包含
            this._finds = function (key, value) {
                //@ts-ignore
                if (Array.isArray(this)) {
                    //@ts-ignore
                    var self = __spreadArray([], this, true);
                    var index_1 = -1;
                    var result_2;
                    if (value || value === 0) {
                        self.map(function (item, idx) {
                            if (item[key] === value) {
                                result_2 = __assign({}, item);
                                index_1 = idx;
                            }
                        });
                    }
                    else {
                        self.map(function (item, idx) {
                            if (item === key) {
                                result_2 = key;
                                index_1 = idx;
                            }
                        });
                    }
                    return {
                        result: result_2,
                        index: index_1
                    };
                }
            };
            //@ts-ignore
            Array.prototype.unique = this._unique;
            //@ts-ignore
            Array.prototype.inline = this._inline;
            //@ts-ignore
            Array.prototype.finds = this._finds;
            //@ts-ignore
            Array.prototype.translate = this._translate;
        }
        return JArr;
    }());

    var DB = /** @class */ (function () {
        function DB(props) {
            var _this = this;
            this.openDB = function (collectName) {
                return new Promise(function (resolve, reject) {
                    var request = window.indexedDB.open(_this._name, 1);
                    request.onsuccess = function (e) {
                        resolve(e.target.result);
                    };
                    request.onerror = function (e) {
                        reject(e.target.result);
                    };
                    request.onupgradeneeded = function (e) {
                        var db = e.target.result;
                        if (!db.objectStoreNames.contains(collectName)) {
                            db.createObjectStore(collectName, { keyPath: 'id', autoIncrement: true });
                        }
                        resolve(e.target.result);
                    };
                });
            };
            this.onPull = function (collectName, index) {
                return new Promise(function (resolve, reject) {
                    _this.openDB(collectName)
                        .then(function (db) {
                        if (index) ;
                        else {
                            var request = db.transaction(collectName).objectStore(collectName).openCursor();
                            var result_1 = [];
                            request.onsuccess = function (res) {
                                if (res.target.result) {
                                    var item = res.target.result;
                                    result_1.push(item.value);
                                    item.continue();
                                }
                                else {
                                    db.close();
                                    resolve(result_1.reverse());
                                }
                            };
                        }
                    })
                        .catch(function (db) {
                        throw db;
                    });
                });
            };
            this.onPush = function (collectName, data) {
                return new Promise(function (resolve, reject) {
                    _this.openDB(collectName)
                        .then(function (db) {
                        var request = db.transaction([collectName], 'readwrite').objectStore(collectName).add(data);
                        request.onsuccess = function () {
                            var ret = db.transaction(collectName).objectStore(collectName).openCursor();
                            var result = [];
                            ret.onsuccess = function (res) {
                                if (res.target.result) {
                                    var item = res.target.result;
                                    result.push(item.value);
                                    item.continue();
                                }
                                else {
                                    db.close();
                                    resolve(result.reverse());
                                }
                            };
                        };
                        request.onerror = function (err) {
                            reject(err);
                            db.close();
                            throw err;
                        };
                    })
                        .catch(function (err) {
                        reject(err);
                        throw err;
                    });
                });
            };
            this.onUpdate = function (collectName, data) {
                return new Promise(function (resolve, reject) {
                    _this.openDB(collectName)
                        .then(function (db) {
                        var request = db.transaction([collectName], 'readwrite').objectStore(collectName).put(data);
                        request.onsuccess = function () {
                            var ret = db.transaction(collectName).objectStore(collectName).openCursor();
                            var result = [];
                            ret.onsuccess = function (res) {
                                if (res.target.result) {
                                    var item = res.target.result;
                                    result.push(item.value);
                                    item.continue();
                                }
                                else {
                                    db.close();
                                    resolve(result.reverse());
                                }
                            };
                        };
                        request.onerror = function (err) {
                            reject(err);
                            db.close();
                            throw err;
                        };
                    })
                        .catch(function (err) {
                        reject(err);
                        throw err;
                    });
                });
            };
            this.onDelete = function (collectName, id, index) {
                return new Promise(function (resolve, reject) {
                    _this.openDB(collectName)
                        .then(function (db) {
                        var request = db.transaction([collectName], 'readwrite').objectStore(collectName).delete(id);
                        request.onsuccess = function () {
                            var ret = db.transaction(collectName).objectStore(collectName).openCursor();
                            var result = [];
                            ret.onsuccess = function (res) {
                                if (res.target.result) {
                                    var item = res.target.result;
                                    result.push(item.value);
                                    item.continue();
                                }
                                else {
                                    db.close();
                                    resolve(result.reverse());
                                }
                            };
                        };
                        request.onerror = function (err) {
                            reject(err);
                            db.close();
                            throw err;
                        };
                    })
                        .catch(function (err) {
                        reject(err);
                        throw err;
                    });
                });
            };
            this._name = props.name;
        }
        return DB;
    }());

    function _typeof(obj) {
      "@babel/helpers - typeof";

      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function (obj) {
          return typeof obj;
        };
      } else {
        _typeof = function (obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }

      return _typeof(obj);
    }

    function deepClone$1(obj) {
      var cache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new WeakMap();
      if (_typeof(obj) !== 'object') return obj; // 普通类型，直接返回

      if (obj === null) return obj;
      if (cache.get(obj)) return cache.get(obj); // 防止循环引用，程序进入死循环

      if (obj instanceof Date) return new Date(obj);
      if (obj instanceof RegExp) return new RegExp(obj); // 找到所属原型上的constructor，所属原型上的constructor指向当前对象的构造函数

      var cloneObj = new obj.constructor();
      cache.set(obj, cloneObj); // 缓存拷贝的对象，用于处理循环引用的情况

      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          cloneObj[key] = deepClone$1(obj[key], cache); // 递归拷贝
        }
      }

      return cloneObj;
    }

    function debounce$1(fn, delay) {
      var timer;
      return function () {
        var _this = this;

        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }

        if (timer) {
          clearTimeout(timer);
        }

        timer = setTimeout(function () {
          fn.apply(_this, args);
        }, delay);
      };
    }

    function throttle$1(fn, delay) {
      var _this = this;

      var last = 0; // 上次触发时间

      return function () {
        var now = Date.now();

        if (now - last > delay) {
          last = now;

          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }

          fn.apply(_this, args);
        }
      };
    }

    var jStorage = storage;
    var JRequest = jRequest;
    var JSocket = Socket;
    var JArray = JArr;
    var JDB = DB;
    var deepClone = deepClone$1;
    var debounce = debounce$1;
    var throttle = throttle$1;
    var main = {
      jStorage: jStorage,
      JSocket: JSocket,
      JRequest: JRequest,
      JArray: JArray,
      JDB: JDB,
      deepClone: deepClone,
      debounce: debounce,
      throttle: throttle
    };

    exports.JArray = JArray;
    exports.JDB = JDB;
    exports.JRequest = JRequest;
    exports.JSocket = JSocket;
    exports.debounce = debounce;
    exports.deepClone = deepClone;
    exports["default"] = main;
    exports.jStorage = jStorage;
    exports.throttle = throttle;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
